package db

import (
	"log"

	"github.com/jmoiron/sqlx"
	_ "github.com/mattn/go-sqlite3"
)

var Db *sqlx.DB

func InitDal() {
	db, err := sqlx.Connect("sqlite3", "data.db")
	if err != nil {
		log.Fatal(err)
	}
	Db = db
	migrate()
}

func migrate() {
	var name []string
	err := Db.Select(&name, "SELECT name FROM sqlite_master WHERE type='table' AND name='history';")
	if err != nil {
		log.Fatal(err)
	}
	if len(name) == 0 {
		schema := `CREATE TABLE history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    method TEXT,
    url TEXT,
    headers TEXT,
    params TEXT,
    body TEXT,
    content_type INTEGER,
    response TEXT,
    date DATE,
    time INTEGER);`
		_, err = Db.Exec(schema)
		if err != nil {
			log.Fatal(err)
		}
	}
}
